package gold.digger;

/**
 * Created by fanzhenyu02 on 2020/3/1.
 */
public class LC43 {

    public String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) {
            return "0";
        }

        String lastMultiStr = "0";
        for (int i = num2.length() - 1; i >= 0; i--) {
            String curMultiStr = multiplySingleStringBit(num1, num2.charAt(i));
            for (int j = 0; j < num2.length() - 1 - i; j++) {
                curMultiStr += "0";
            }
            lastMultiStr = stringAdd(curMultiStr, lastMultiStr);
        }

        return lastMultiStr;
    }

    public String multiplySingleStringBit(String num1, char num2) {
        StringBuilder res = new StringBuilder();
        int multi = num2 - '0';
        int lastStep = 0;
        int curRes = 0;
        for (int i = num1.length() - 1; i >= 0; --i) {
            int curBit = num1.charAt(i) - '0';
            curRes = curBit * multi + lastStep;
            res.insert(0, curRes % 10);
            lastStep = curRes / 10;
        }

        if (lastStep > 0) {
            res.insert(0, lastStep);
        }
        return res.toString();
    }


    public String stringAdd(String num1, String num2) {
        StringBuilder res = new StringBuilder();
        if (num1.length() < num2.length()) {
            String temp = num2;
            num2 = num1;
            num1 = temp;
        }

        int curSum = 0;
        int lastStep = 0;
        int i = num2.length() - 1, j = num1.length() - 1;
        for (; i >= 0; i--, j--) {
            curSum = num1.charAt(j) - '0' + num2.charAt(i) - '0' + lastStep;
            res.insert(0, curSum % 10);
            lastStep = curSum / 10;
        }

        for (; j >= 0; --j) {
            curSum = num1.charAt(j) - '0' + lastStep;
            res.insert(0, curSum % 10);
            lastStep = curSum / 10;
        }

        if (lastStep > 0) {
            res.insert(0, lastStep);
        }

        return res.toString();
    }

    public static void main(String[] args) {
        LC43 an = new LC43();
        String num1 = "123", num2 = "456";

        System.out.println(an.multiply(num2, num1));
//        System.out.println(an.stringAdd("189", "68"));
    }
}
